package com.aidex.system.service.impl;

import com.aidex.common.constant.Constants;
import com.aidex.common.core.mybatisplus.core.ServicePlusImpl;
import com.aidex.common.utils.RedisUtils;
import com.github.pagehelper.PageInfo;
import com.aidex.common.core.domain.model.LoginUser;
import com.aidex.common.core.service.BaseServiceImpl;
import com.aidex.common.utils.SecurityUtils;
import com.aidex.system.domain.SysTableConfig;
import com.aidex.system.mapper.SysTableConfigMapper;
import com.aidex.system.service.SysTableConfigService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * 个性化配置Service业务层处理
 * @date 2021-03-31
 */
@Service
public class SysTableConfigServiceImpl extends ServicePlusImpl<SysTableConfigMapper, SysTableConfig,SysTableConfig> implements SysTableConfigService
{

    /**
     * 获取单条数据
     * @param sysTableConfig
     * @return
     */

    public SysTableConfig get(SysTableConfig sysTableConfig)
    {
        return super.getById(sysTableConfig);
    }
    @Override
    public SysTableConfig getInfoByTableKey (String tableKey)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        return RedisUtils.getCacheObject(getCacheKey(tableKey));
    }

    private String getCacheKey(String configKey) {
        return Constants.SYS_CONFIG_KEY + configKey;
    }

    @Override
    public SysTableConfig getInfoByTableKeyFormDb (String tableKey)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysTableConfig sysTableConfig = new SysTableConfig();
        sysTableConfig.setTableKey(tableKey);
        sysTableConfig.setUserId(loginUser.getUser().getId());
        List<SysTableConfig> sysTableConfigList = baseMapper.getInfoByTableKey(sysTableConfig);
        if(!CollectionUtils.isEmpty(sysTableConfigList)){
            return sysTableConfigList.get(0);
        }else{
            return null;
        }
    }
    /**
     * 查询个性化配置列表
     * @param sysTableConfig
     * @return
     */


    /**
     * 保存个性化配置
     * @param sysTableConfig
     * @return 结果
     */
    @Override
    public boolean save(SysTableConfig sysTableConfig)
    {
        boolean saveFlag  = false;
        try{
            saveFlag  = super.save(sysTableConfig);
            RedisUtils.setCacheObject(sysTableConfig.getTableKey(),sysTableConfig);
        }catch (Exception e){
           //保存异常清除缓存
            RedisUtils.deleteObject(getCacheKey(sysTableConfig.getTableKey()));
        }
        return saveFlag;
    }

    /**
     * 批量删除个性化配置
     * @param ids 需要删除的个性化配置ID
     * @return 结果
     */
    @Transactional(readOnly = false)
    @Override
    public int deleteSysTableConfigByIds(String[] ids)
    {
        return baseMapper.deleteSysTableConfigByIds(ids);
    }
}
